package com.tr.gaoji;

/**
 * @author TRasdzz
 * @version 1.0
 * @since create in 2021/3/11 23:13
 */
//测试：生产者消费者模式 --> 利用缓冲区解决：管程法

//生产者，消费者，产品，缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Productor(synContainer).start();

        new Customer(synContainer, "a").start();
        new Customer(synContainer, "b").start();
        new Customer(synContainer, "c").start();



    }
}

//生产者
class Productor extends Thread{


    SynContainer synContainer ;

    public Productor(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            Chicken chicken = new Chicken(i);
            synContainer.push(chicken);
            System.out.println("生产者放入了第" + chicken.id + "只鸡");
        }
    }
}

//消费者
class Customer extends Thread{

    SynContainer synContainer ;

    public Customer(SynContainer synContainer,String name){
        super(name);
        this.synContainer = synContainer;
    }

    @Override
    public void run() {

        for (int i = 0; i < 20; i++) {
            Chicken chicken = synContainer.pop();
            System.out.println("消费者"+Thread.currentThread().getName()+"取出了第" + chicken.id + "只鸡");
        }
        System.out.println("看看");
    }
}

//产品
class Chicken {
    int id;//鸡的编号

    public Chicken(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer{
    //容器的大小
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    //存放
    public synchronized void push(Chicken chicken){
        //如果满 停止放鸡 等待消费
        while (count == chickens.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有满，丢入鸡
        chickens[count] = chicken;
        count++;

        //通知消费
        this.notifyAll();
    }
    //消费
    public synchronized Chicken pop(){
        //如果没鸡 等待生产
        while (count == 0){
            try {

                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //消费鸡
        count--;
        Chicken chicken = chickens[count];

        //通知生产
        this.notifyAll();
        return chicken;
    }
}